package com.ithuangyl.common.net;

import android.content.Context;
import android.util.Log;

import com.ithuangyl.common.config.Latte;
import com.ithuangyl.common.loader.LatteLoader;
import com.ithuangyl.common.loader.LoaderStyle;
import com.ithuangyl.common.net.callback.IError;
import com.ithuangyl.common.net.callback.IFailure;
import com.ithuangyl.common.net.callback.IRequest;
import com.ithuangyl.common.net.callback.ISuccess;
import com.ithuangyl.common.net.callback.RequestCallbacks;

import java.util.HashMap;

import retrofit2.Call;

/**
 * author : itHuang
 * e-mail : ithuangyl@163.com
 * date   : 2020/7/15 21:42
 */
public class RestClient {

    private static final String TAG = "RestClient";
    private final HashMap<String, Object> PARAMS;
    private final String URL;
    private final Class<?> CLAZZ;
    private final IRequest REQUEST;
    private final ISuccess<?> SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;
    private final LoaderStyle LOADER_STYLE;
    private final Context CONTEXT;

    RestClient(String url, HashMap<String, Object> params, Class<?> clazz, IRequest iRequest, ISuccess<?> iSuccess, IFailure iFailure, IError iError,Context context, LoaderStyle loaderStyle) {
        this.URL = url;
        this.PARAMS = params;
        this.CLAZZ = clazz;
        this.REQUEST = iRequest;
        this.SUCCESS = iSuccess;
        this.FAILURE = iFailure;
        this.ERROR = iError;
        this.CONTEXT =context;
        this.LOADER_STYLE = loaderStyle;
    }

    public static RestClientBuilder builder() {
        return new RestClientBuilder();
    }

    public void get() {
        request(HttpMethod.GET);
    }

    private void request(HttpMethod method) {
        final RestService service = RestCreator.getService();
        Call<String> call = null;

        if (REQUEST != null) {
            REQUEST.onRequestStart();
        }
        if (LOADER_STYLE!=null){
            LatteLoader.showLoading(CONTEXT,LOADER_STYLE);
        }
        switch (method) {
            case GET:
                call = service.get(URL, PARAMS);
                break;
            case POST:
                call = service.post(URL, PARAMS);
                break;
        }

        if (call != null) {
            call.enqueue(new RequestCallbacks<>(CLAZZ,REQUEST, SUCCESS, FAILURE, ERROR, LOADER_STYLE));
        } else {
            Log.e(TAG, "call is null");
        }
    }
}
